package com.mspbots.teams.sync.service;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

import javax.validation.constraints.NotEmpty;

/**
 *
 */
@Log4j2
@Component
public class TeamsGetClient {

    protected final WebClient webClient;
    @NotEmpty
    private String teamsApiUrl = "http://mspbotsint.azurewebsites.net/api";

    public TeamsGetClient() {
        this.webClient = WebClient.builder().baseUrl(teamsApiUrl)
//                .defaultHeader("Authorization", "Bearer " + tSheetsProperties.getToken())
                .build();
    }

    public Mono<JsonNode> getUserRepository(MultiValueMap<String, String> params) {

        log.debug("teams get users by is params:{}.", params);

        Mono<JsonNode> result = this.request("/graph/users", params);
        return result;

    }


    protected Mono<JsonNode> request(String path, MultiValueMap<String, String> queryParams) {
        return this.webClient.get().uri(uriBuilder -> uriBuilder.path(path).queryParams(queryParams).build())
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .retrieve()
                .bodyToMono(JsonNode.class)
                .doOnError(WebClientResponseException.class, err -> {
                    log.debug("get teams user :{},msg:{}", err.getRawStatusCode(), err.getResponseBodyAsString());
                    throw new RuntimeException(err.getResponseBodyAsString());
                });
    }
}
